<?php

namespace app\admin\controller\inventory;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use fast\Auth;
use think\exception\PDOException;
use app\admin\model\information\Warehouse;
use app\admin\model\information\Oausersuperior;
/**
 * 领料单
 *
 * @icon fa fa-circle-o
 */
class Material extends Backend
{

    /**
     * Material模型对象
     * @var \app\admin\model\inventory\MaterialList
     */
    protected $info = null;
    protected $model = null;
    protected $modelView = null;
    protected $modelInv = null;
    protected $modelCode = null;
    protected $modelKc = null;
    protected $modelOaapi = null;
    protected $modelOaflow15 = null;
    
    protected $noNeedLogin = ['add','addPcDetail','inventoryList','clearData','addMaterialList','index','getData','edit','getOaitemname'];

    public function _initialize()
    {
        $this->request->filter([
            'strip_tags',
            'trim'
        ]);
        
        $this->info = new \app\admin\model\inventory\Material;
        $this->model = new \app\admin\model\inventory\MaterialList;
        $this->modelInv = new \app\common\model\Inventory;
        $this->modelView = new \app\admin\model\inventory\MaterialListView;
        $this->modelCode = new \app\admin\model\Mcode;
        $this->modelKc = new \app\admin\model\inventory\Wmskc;
        //$this->modelOaapi = new \app\admin\model\Oaapi;
        //$this->modelOaflow15 = new \app\admin\model\information\Oaflow15;
        
        parent::_initialize();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    //选择器界面 

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        
        //['搜索字段名'=>'页面字段名']
        /* setParam([
            'order_date' => 'order_date'
        ]); */
        $this->searchFields = 'material_code,inventory_number,inv_name,specification,unit,store_unit,warehouse_name,fOrderBillNo,cBatch';
       
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
         
        $list = $this->modelView::where($where)->paginate($limit);
            /*if($list){
                foreach ($list as &$item){
                    $info = $this->info->where([
                        'material_code' => $item->material_code,
                    ])->find();
                    
                    //更新部门编码
                    if($info){
                        $u8_dpt_code = U8department::where('cDepName',$info->fitemssname)->value('cDepCode');
                        if($u8_dpt_code){
                            $info->cdepcode = $u8_dpt_code;//项目名，当部门名称
                            $info->save();
                        }
                    }
                    
                    //更新拣货路径
                    if(!$item->tj_shelves_id){
                        $tj_arr = $this->modelInv::getTjWhShByInvNumber($item->inventory_number);
                        if($tj_arr){
                            $item->warehouse_id = $tj_arr['lastest_warehouse_id'];
                            $item->tj_shelves_id = $tj_arr['lastest_shelves_id'];
                            $item->save();
                        }
                    }
                }
            }*/
            
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /*
     * 物料列表，领料界面
     *   */
    public function inventoryList()
    {
        //设置过滤方法
        $this->searchFields = 'number,name,specification,unit,name_specification';
        $params = $this->request->param();
        
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        
        //有无图标识
        $op = $this->request->get("op", '', 'trim');
        $op = (array)json_decode($op, true);
        $filter = $this->request->get("filter", '');
        $warehouse_id = $this->request->get('warehouse_id',2);
        
        $where2 = [];
        if($filter){
            $filter=urldecode($filter);
            $filter=json_decode($filter,TRUE);
            if(isset($filter['image_url'])){
                //0无，1有
                if($filter['image_url']){
                    $where2['image_url'] = ['neq','not null']; //不为空
                }else{
                    $where2['image_url'] = null;
                }
                unset($filter['image_url'],$op['image_url']);
            }
            if(isset($filter['kcflag'])){
                //0全部，1有库存
                if($filter['kcflag']){
                    //获取u8所有，有库存的物料编码
                    $inv_code_arr = $this->modelKc::getWmsKcCodes();
                    if($inv_code_arr){
                        $where2['number'] = ['IN',$inv_code_arr];
                    }
                }
                unset($filter['kcflag'],$op['kcflag']);
            }
            $this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
        }
        
        //不要显示良品，则读取u8通过过来的物料
        if(!config('site.app_show_lp_flag')){
            $where2['source'] = 2;
        }
        
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        
        $list = $this->modelInv
        ->where($where)
        ->where($where2)
        ->where([
            'switch' => 1
        ])
        ->field('id,image_url,number,name,specification,unit_code,unit,shelves_id,warehouse_id')
        ->order($sort, $order)
        ->paginate($limit);
        
        if($list->items()){
            foreach ($list->items() as $item){
                $item->iQuantity = $this->modelKc::getKcQty($warehouse_id,0, $item->number);//默认五金仓
                
                //生成缩略图
                /*if($item->image_url){
                    $arr = explode(',', $item->image_url);
                    foreach ($arr as $path){
                        if(!file_exists(cdnurl($path.'.s.png',true))){
                            //缩略图
                            $imagePath = cdnurl($path,true);
                            $img = \think\Image::open($imagePath);
                            $img->thumb(400,400);
                            $small_img = ROOT_PATH . 'public'.$path.'.s.png';
                            $img->save($small_img);//保存
                        }
                    }
                    $item->is_thumb = true;
                }*/
            }
        }
        
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $ids_arr = explode(',', $ids);
        $single = $this->request->get('single',0);
        
        $code = Db::name('material_list')->where(['id'=>$ids])->value('material_code');
        $info = $this->info::where(['material_code'=>$code])->find();
        $info['qrcode'] = getQrcodeUrl($code);
        
        if(!$single&&count($ids_arr)==1){
            $list =$this->model->alias('m')
            ->join('inventory i','i.number=m.inventory_number','left')
            ->join('warehouse w','w.id=m.warehouse_id','left')
            ->join('shelves sh','sh.id=m.tj_shelves_id','left')
            ->field('m.*,i.name,i.number,i.specification,i.attributes,i.unit,w.name as wname,concat(sh.name,"-",sh.number) tj_shelves_name')
            ->where(['m.material_code'=>$code])
            ->order('m.inventory_number')
            ->select();
        }else{
            $list =$this->model->alias('m')
            ->join('inventory i','i.number=m.inventory_number','left')
            ->join('warehouse w','w.id=m.warehouse_id','left')
            ->join('shelves sh','sh.id=m.tj_shelves_id','left')
            ->field('m.*,i.name,i.number,i.specification,i.attributes,i.unit,w.name as wname,concat(sh.name,"-",sh.number) tj_shelves_name')
            ->where([
                'm.id'=>['IN',$ids_arr]
            ])
            ->order('m.inventory_number')
            ->select();
        }
        
        $this->assign('row',$info);
        $this->assign('list_json',json_encode($list));
        $flag = $this->request->get('flag','');
        
        return $this->fetch($flag);
    }

    
    public function getData(){
        Db::startTrans();
        try {
            $type = $this->request->post('type','kis');
            if($type=='kis'){
                //$this->info->getMaterialData('','',1);//发货通知单
                //$this->info->getMaterialData('','',2);//材料清单
                $this->info->getMaterialData('','',3);//销售出库单
                Log::info('计划任务-KIS领料同步完成');
            }else{
                $this->modelOaflow15->getOaData();
                //主动获取oa数据的，不需要考虑并发外发
                Log::info('计划任务-OA领料同步完成');
            }
            Db::commit();
            $this->success("同步完成");
        }catch (Exception $e){
            Db::rollback();
            Log::error('计划任务-U8领料同步失败'.$e->getMessage());
            $this->error($e->getMessage());
        }
    }


    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }

        $count = 0;
        $check_status = $values['status'] + 0;

        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                //$count += $item->allowField(true)->isUpdate(true)->save($values);
                $this->check($item->material_code, $check_status);
                $count++;
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }
    
    public function check($code,$status){
        Db::name('material')->where(['material_code'=>$code])->update([
            'status'=>$status,
            'sh_time' => $status==1?date('Y-m-d',time()):null
        ]);
    }
    
    /*
     * 
     *   */
    public function addPcDetail(){
        $admin_id = isset($this->auth->id)?$this->auth->id:0;
        
        if (false === $this->request->isPost()) {
            //$this->error(__('Invalid parameters'));
            $warehouse_id = $this->request->get('warehouse_id',2);
            $list =Db::name('pc_material_list')->alias('m')
            ->join('warehouse w','w.id=m.warehouse_id','left')
            ->field('m.*,w.name as wname')
            ->where([
                'admin_id' => $admin_id
            ])->select();
            
            if($list){
                foreach ($list as $k=>$item){
                    $list[$k]['iQuantity'] = $this->modelKc::getKcQty($warehouse_id,0, $item['number']);//getU8KcQty($warehouse_id, $item['number']);
                }
            }
            
            $this->assign('warehouse_arr',Warehouse::getList());
            $this->assign('list_json',json_encode($list));
            $this->assign('code',$this->modelCode::getCode(0));
            
            $this->assign('oa_citem_arr',config('site.oa_cItem_arr'));
            $this->assign('oa_type_arr',config('site.oa_type_arr'));
            
            return $this->fetch('pc_material_list');
        }else{
            $id = $this->request->post('id',0);
            $nums = $this->request->post('nums',0);
            try{
                if(!$id||!$nums){
                    exception("参数错误");
                }
                $inventory = db('inventory')->where('id',$id)->find();
                if(!$inventory){
                    exception("找不到物料ID{$id}");
                }
                
                $check = db('pc_material_list')->where([
                    'inv_id' => $id,
                    'admin_id' => $admin_id
                ])->find();
                if($check){
                    db('pc_material_list')->where([
                        'inv_id' => $id,
                        'admin_id' => $admin_id
                    ])->setInc('nums',$nums);
                }else{
                    $images_arr = explode(',', $inventory['image_url']);
                    
                    db('pc_material_list')->insert([
                       'inv_id' => $id,
                        'name' => $inventory['name'],
                        'number' => $inventory['number'],
                        'specification' => $inventory['specification'],
                        'image_url' => $images_arr[0],
                        'unit' => $inventory['unit'],
                        'unit_code' => $inventory['unit_code'],
                        'nums' => $nums,
                        'admin_id' => $admin_id,
                        'createtime' => time()
                    ]);
                }
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success();
        }
    }
    
    /*
     * 清空数据
     *   */
    public function clearData(){
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $admin_id = isset($this->auth->id)?$this->auth->id:0;
        try{
            Db::name('pc_material_list')
            ->where([
                'admin_id' => $admin_id
            ])->delete();
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success();
    }
    
    /*
     * 生成领料单
     *   */
    public function addMaterialList(){
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        
        $admin_id = isset($this->auth->id)?$this->auth->id:0;
        Db::startTrans();
        try{
            
            $params = $this->request->param('row/a');
            if($params['basic'] == '[]'){
                exception('请选择物料');
            }
            if(!$params['user_id']){
                exception('请选择领料人');
            }
            
            $warehouse_code = db('warehouse')->where('id',$params['warehouse_id'])->value('number');
            if(!$warehouse_code){
                exception('请选择仓库');
            }
            
            if(!config('site.backoa')){
                exception('请先开启回写OA配置');
            }
            
            $items = json_decode($params['basic'],true);
            /* db('material')->insert([
                'material_code' => $params['code'],
                'order_date' => $params['code_date'],
                'source' => 3,
                //'sh_time' => $params['code_date'],
                'createtime' => date('Y-m-d H:i:s',time()),
                'cUser_Id' => $params['cUser_Id'],
                'cUser_Name' => $params['cUser_Name'],
                'cdepname' => $params['cdepname'],
                'status' => 1,//默认审核过
                'crdcode' => '22',
                'crdname' => '生产领用'
            ]); */
            
            $oa_citem_arr = config('site.oa_cItem_arr');
            $oa_type_arr = config('site.oa_type_arr');
            
            $oaArr = [
                'DATA_1' => $params['code'],//申请单编号
                'DATA_2' => $params['user_name'],//申请人
                'DATA_3' => $params['dept_name'],//申请部门
                'DATA_5' => $params['user_id'],//领料人id oa的用户账号id user
                'DATA_5_TEXT' => $params['user_name'],//领料人文本
                'DATA_6' => $params['dept_name'],//领料部门
                'DATA_8' => $params['code_date'],
                //'DATA_9' => $params['oa_type']==2?'劳保用品':'其他',
                'DATA_11' => $params['remark'],//备注
                'DATA_12' => $params['code_date'],//申请日期
                'DATA_18' => $params['user_name'],//发起人
                'DATA_19' => date('Y-m-d H:i:s'),
                //'DATA_15' => '车间主任,员工,知识产权系统操作员',//领料人角色
                'DATA_16' => $params['oa_type'],//类别
                'DATA_16_TEXT' => $oa_type_arr[$params['oa_type']],//类别文本
                'DATA_33' => $params['oa_citem_type'],//项目大类ID
                'DATA_33_TEXT' => $oa_citem_arr[$params['oa_citem_type']],//项目大类文本
                'DATA_34' => $params['oa_item_name'],//$params['oa_item_name_id'],//项目名ID
                'DATA_34_TEXT' => $params['oa_item_name'],//项目名文本
                'DATA_35' => 64,//
                'DATA_35_TEXT' => '流程说明',
                'DATA_38' => '终端机'//终端机标识
            ];
            
            $list = [];
            foreach ($items as $k=>$item){
                //$kc = $this->modelKc::getTjWhShID($item['number'],$warehouse_code);
                /* $list[] = [
                    'warehouse_id' => $params['warehouse_id'],
                    'tj_shelves_id' => intval($kc['shelves_id']),
                    'inv_id' => $item['inv_id'],
                    'cWhcode' => $warehouse_code,
                    'material_code' => $params['code'],
                    'row_id' => $k+1,
                    'inventory_number' => $item['number'],
                    'quantity' => $item['nums'],
                    'sh_time' => $params['code_date'],
                    'createtime' => date('Y-m-d H:i:s',time())
                ]; */
                $inventory = $this->modelInv::where('number',$item['number'])->find();
                /*$oa_inventory = Db::connect('database.forth')->table('custom_data_1003')
                ->where('field_4',$item['number'])
                ->find();
                
                if(!$oa_inventory){
                    exception("oa找不到物料编码[{$item['number']}]");
                }*/
                
                $list[] = [
                    'DATA_10_1' => $inventory->specification==''?'null':$inventory->specification,//规格
                    'DATA_10_2' => $inventory->unit,//单位
                    'DATA_10_3' => $item['nums'],//领取数量
                    'DATA_10_4' => '',//备注
                    'DATA_10_6' => $item['number'],//编码
                    'DATA_10_7' => $item['number'],//编码
                    //'DATA_10_7' => $oa_inventory['data_id'],//oa物料id   custom_data_1003,
                    'DATA_10_7_TEXT' => $inventory->name,
                    'DATA_10_8' => $inventory->classification_id //物料分类
                ];
            }
            
            $oaArr['DATA_10'] = $list;
            
            $run_id = $this->modelOaapi::flowSave($oaArr,$params['user_id']);
            
            $cur_flow_id = config('site.cur_flow_id');//71正式  测试10
            $next_flow_id = 0;
            //判断下一个流程id
            if($params['dept_name']=='质量部'||strpos($params['dept_name'],'车间') !== false){//质量部orxx车间
                $next_flow_id = config('site.next_flow_id2');;//终端-上级 398 测试12
            }else{
                $next_flow_id = config('site.next_flow_id');;//终端-部门负责人399  测试13
            }
            
            $superior_user_id = Oausersuperior::getSuperior($params['user_id']);
            
            $turn_data = [
                "process_transact_user" => $superior_user_id,//'admin',
                "process_host_user" => $superior_user_id,//'admin',
                "next_flow_process" => $next_flow_id,
                "flow_process" => $cur_flow_id
            ];
            $res = $this->modelOaapi::flowTurning($run_id,$turn_data,$params['user_id']);//结束当前流程，向下一个流程流转
            
            myLog('终端机提交领料申请',['单号'=>$params['code'],'run_id'=>$run_id]);
            myLog('终端机提交领料申请下一个流程ID',['单号'=>$params['code'],'next_flow_id'=>$next_flow_id]);
            //db('material_list')->insertAll($list);
            
            db('pc_material_list')->where(['admin_id' => $admin_id])->delete();
            
            $this->modelCode::setStatus($params['code']);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            myLog('终端机-领料申请-异常',$e->getMessage());
            db('pc_material_list')->where(['admin_id' => $admin_id])->delete();
            $this->error($e->getMessage());
        }
        $this->success('','',json_encode(['action' => 'add']));
    }
    
    // 导出excel
    public function export()
    {
        // $this->relationSearch = true;
        if ($this->request->isPost()) {
            set_time_limit(0);
            $code = $this->request->post('code','');
            try {
                if(!$code){
                    exception('单号参数不能为空');
                }
                $info = Db::name('material')->where(['material_code'=>$code])
                ->field('order_date,status,crdname,cdepname,cUser_Name')
                ->find();
                if(!$info){
                    exception('不存在该领料单');
                }
                
                $line = 1;
                $list =Db::name('material_list')->alias('m')
                    ->join('inventory i','i.number=m.inventory_number','left')
                    ->join('warehouse w','w.id=m.warehouse_id','left')
                    ->join('shelves sh','sh.id=m.tj_shelves_id','left')
                    ->field('m.*,i.name,i.number,i.specification,i.attributes,i.unit,w.name as wname,sh.name tj_shelves_name')
                    ->where(['m.material_code'=>$code])
                    ->select();
                if(!$list){
                    exception('该领料单无明细记录');
                }
                
                $nickname = $this->auth->nickname;
                $excel = new Spreadsheet();
                $excel->getProperties()
                ->setCreator($nickname)
                ->setLastModifiedBy($nickname)
                ->setTitle("领料单")
                ->setSubject("Subject");
                
                $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
                $excel->getDefaultStyle()->getFont()->setSize(12);
                $worksheet = $excel->setActiveSheetIndex(0);
                $worksheet->setTitle('领料单');
                
                $new_basic_arr = [];
                foreach ($list as $keys => $row) {
                    $new_basic_arr[$keys]['领料单编号'] = $list[$keys]['material_code'];
                    $new_basic_arr[$keys]['单据日期'] = $info['order_date'];
                    $new_basic_arr[$keys]['申请部门'] = $info['cdepname'];
                    $new_basic_arr[$keys]['申请人'] = $info['cUser_Name'];
                    $new_basic_arr[$keys]['仓库'] = $list[$keys]['wname'];
                    $new_basic_arr[$keys]['拣货路径'] = $list[$keys]['tj_shelves_name'];
                    $new_basic_arr[$keys]['物料编号'] = $list[$keys]['number'];
                    $new_basic_arr[$keys]['物料名称'] = $list[$keys]['name'];
                    $new_basic_arr[$keys]['规格'] = $list[$keys]['specification'];
                    $new_basic_arr[$keys]['单位'] = $list[$keys]['unit'];
                    $new_basic_arr[$keys]['数量'] = $list[$keys]['quantity'];
                }
                
                foreach ($new_basic_arr as $index => $item) {
                    $line++;
                    $col = 0;
                    foreach ($item as $keys => $value) {
                        $worksheet->setCellValueByColumnAndRow($col + 1, $line, $value);
                        $worksheet->getStyleByColumnAndRow($col + 1, $line)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                        // $worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);
                        $col++;
                    }
                }
                // 配置表头
                $first = array_keys($new_basic_arr[0]);
                foreach ($first as $index => $item) {
                    $worksheet->setCellValueByColumnAndRow($index + 1, 1, __($item));
                    // $worksheet->getColumnDimension($index)->setAutoSize(true);
                }
                // A-Z有用，后面就没用了
                foreach ($worksheet->getColumnIterator() as $column) {
                    $worksheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true);
                }
                // 加范围A-B有用，后面就没用了
                // foreach (range('A','B') as $col) {
                //     $worksheet->getColumnDimension($col)->setAutoSize(true);
                    // }
                $excel->createSheet();
                // Redirect output to a client’s web browser (Excel2007)
                $title = '领料单'.date("YmdHis");
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
                header('Cache-Control: max-age=0');
                // If you're serving to IE 9, then the following may be needed
                header('Cache-Control: max-age=1');
                
                // If you're serving to IE over SSL, then the following may be needed
                header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
                header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
                header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
                header('Pragma: public'); // HTTP/1.0
                
                
                $objWriter = IOFactory::createWriter($excel, 'Xlsx');
                $objWriter->save('php://output');
                return;
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
        }
    }
    
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        
        $delsFlag = $this->request->post("dels",0);
        if($delsFlag){
            //整单删除
            $order_code_arr = $this->model->where($pk, 'in', $ids)
            ->group('material_code')
            ->column('material_code','id');
            
            //所有明细记录
            $list = $this->model->where([
                'material_code' => ["IN",$order_code_arr]
            ])
            ->select();
        }else{
            //删除明细
            $list = $this->model->where($pk, 'in', $ids)->select();
        }

        //$model = $this->model::get($ids);
        if(!$list){
            $this->error('不存在该领料单');
        }

        $count = 0;
        Db::startTrans();

        foreach($list as $model){
            if(db('temporary')->where([
                'source_code' => $model->material_code,
                'status' => 1
            ])->value('id')){
                $this->error('该领料单已被PDA单据引用，无法删除');
            }
        }
        
        try {
            $count++;
            //整单删除
            //$this->model::where('material_code',$model->material_code)->delete();
            //$this->info::where('material_code',$model->material_code)->delete();
            foreach($list as $model){
                $model->delete();
            }
            if(!$this->model::where('material_code',$model->material_code)->find()){
                //删表头
                $this->info::where('material_code',$model->material_code)->delete();
            }

            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    
    public function getOaitemname(){
        $this->searchFields = 'data_id,field_3';
        $this->selectpageFields = 'data_id,field_3';
        $this->dataLimit = '';
        //$this->dataLimitField = 'data_id';
        
        //$this->or
        $this->model = new \app\admin\model\information\Oaitem;
        
        return parent::selectpage();
        
        /*
         * select field_3 from custom_data_1032 where field_5="#DATA_33#" and field_4=1 order by field_3
         *   */
    }
}
